<?php
/**
 * Created by PhpStorm.
 * User: tom_xia
 * Date: 2018/8/9
 * Time: 21:10
 * 用户登录
 */
require_once dirname(__DIR__) . "/common.php";
use app\cls\tom\Response;
use app\cls\tom\Tools;

if(empty($_POST["code"]) || empty($_POST["raw_user_data"])  || empty($_POST["wx_sign"]) ){
    Response::output(-1,"参数错误");
}
$code = $_POST["code"];
$rawUserData = $_POST["raw_user_data"];
$wxSign = $_POST["wx_sign"];
$rawUserDataArr = @json_decode($rawUserData,true);
if(empty($rawUserDataArr["nickName"]) || empty($rawUserDataArr["avatarUrl"])){
    Response::output(-1,"数据格式错误");
}

try {
    $appKey = WX_PUBLIC_APP_ID;
    $appSecret = WX_PUBLIC_APP_SECRECT;
    $result = Tools::curl("https://api.weixin.qq.com/sns/jscode2session", [
        "appid" => $appKey, "secret" => $appSecret,
        "js_code" => $code, "grant_type" => "authorization_code"]);
    $res = @json_decode($result,true);
    if(!isset($res["openid"])){
        Response::output(-1,"服务器异常 msg==>".$res["errcode"].":".$res["errmsg"]);
    }
    Tools::writeLog(["detail"=>$res,"key"=>"login"]);
    $sessionKey = $res["session_key"];
    //数据签名校验
    if(sha1($rawUserData.$sessionKey) != $wxSign){
        Response::output(-1,"数据可能已经被串改");
    }
    $userInfo = json_decode($rawUserData,true);
    $userInfo["open_id"] = $res["openid"];
    $userService = new \app\service\User();
    $re = $userService->login($userInfo);
    Response::outputSelf($re);
} catch (Exception $e) {
    Response::output(-1,"登录失败 msg==>".$e->getMessage());
}


